﻿@page "/User/Login"
@using Jx.Toolbox.Extensions
@using JxAudio.Web.Components.Layout
@using JxAudio.Web.Vo
@using Microsoft.Extensions.Localization
@layout EmptyLayout

@inject AjaxService AjaxService
@inject SwalService SwalService
@inject IStringLocalizer<Login> Localizer

<div class="container">
    <div class="row">
        <div class="col-12">
            <Card class="shadow-lg border-0 my-5">
                <BodyTemplate>
                    <div class="login-item login-item-avatar">
                        <div class="text-center">
                            <Avatar Url="./Images/logo.png" IsCircle="true" Size="Size.ExtraExtraLarge" />
                            <h4>JxAudio</h4>
                        </div>
                        <ValidateForm Model="@LoginVo" OnValidSubmit="DoLogin" ShowLabel="false">
                            <BootstrapInput @bind-Value="LoginVo.UserName"  />
                            <BootstrapPassword @bind-Value="LoginVo.Password" />
                            <Checkbox @bind-Value="LoginVo.IsKeep" ShowAfterLabel="true" />
                            <Button Text="@Localizer["Login"]" Color="Color.Primary" ButtonType="ButtonType.Submit"></Button>
                        </ValidateForm>
                    </div>
                </BodyTemplate>
            </Card>
        </div>
    </div>
</div>


@code {
    private LoginVo LoginVo { get; set; } = new();

    [SupplyParameterFromQuery]
    public string? ReturnUrl { get; set; }

    private async Task DoLogin(EditContext arg)
    {
        var document = await AjaxService.InvokeAsync(new AjaxOption()
        {
            Url = "/api/User/Login",
            Data = LoginVo
        });
        
        if (document?.RootElement.GetProperty("code").GetInt32() == 200)
        {
            if (ReturnUrl.IsNullOrEmpty())
            {
                await AjaxService.Goto("/");
            }
            else
            {
                await AjaxService.Goto(ReturnUrl!);
            }
        }
        else
        {
            await SwalService.Show(new SwalOption()
            {
                Category = SwalCategory.Error,
                Content = document?.RootElement.GetProperty("message").GetString() ?? Localizer["LoginFailContent"],
                Title = @Localizer["LoginFail"]
            });
        }
    }

}